error = require '../error'
log = require '../log'
EntityService = require '../service/EntityService'

# 前端回调和服务器端回调
exports.CallbackSource = {page: 'page', server: 'server'}

states = {NotPay: 0, Success: 1, Fail: 2}
exports.states = states

exports.Providers = {AlipayWeb: "AlipayWeb", WeixinPay: "WeixinPay"}

exports.gCreatePayment = (ctx, provider, amount, business, businessId) ->
    payment = {state: states.NotPay, provider, amount, business, businessId}
    payment._id = yield from EntityService.gCreate(ctx, 'F_Payment', payment)
    payment

# 更新支付状态（处理回调）
exports.gUpdatePaymentState = (ctx, paymentId, newState, providerFlowNo, amount, buyer)->
    log.pay.info 'change state', {paymentId, newState, providerFlowNo, amount, buyer}

    payment = yield from EntityService.gFindOneById(ctx, null, 'F_Payment', paymentId)
    throw new error.UserError('PayTranNotFound') unless payment

    if amount != payment.amount
        log.pay.error 'Bad amount', {expectAmount: payment.amount, actualAmount: amount, paymentId, providerFlowNo}
        throw new error.UserError('BadAmount')

    if payment.state == newState
        log.pay.info "change PayTran to current state", {paymentId, state: newState}
    else if payment.state == states.NotPay and (newState == states.Success || newState == states.Fail)
        patch = {state: newState, stateDecidedOn: new Date(), providerFlowNo, buyer}
        yield from EntityService.gUpdateMany(ctx, [{_id: payment._id, _version: payment._version}], patch)
    else
        log.pay.error "Illegal state change", {from: payment.state, to: newState, paymentId}
        throw new error.UserError('PayTranStateChangeIllegal')




